package com.asggo.g21.controller;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.asggo.g21.dto.LoginDTO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2023/12/21 16:48
 */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class BaseControllerTests {

  @Autowired
  protected MockMvc mockMvc;

  protected String tokenName;

  protected String tokenValue;

  final String username = "lannlife";
  final String password = "Tuantuan216";

  @BeforeEach
  void init() throws Exception {

    LoginDTO user = new LoginDTO();
    user.setUsername(username);
    user.setPassword(password);

    String contentAsString = mockMvc
        .perform(
            post("/user/sign/in")
                .content(JSONUtil.toJsonStr(user))
                //.header("api-key", "")
                .contentType(APPLICATION_JSON)
                .characterEncoding("UTF-8"))
        .andDo(print())
        .andExpect(status().is2xxSuccessful())
        .andReturn()
        .getResponse()
        .getContentAsString();

    SaTokenInfo tokenInfo = JSONUtil.toBean(contentAsString,
        new TypeReference<>() {
        }, true);
    if (tokenInfo != null) {
      tokenName = tokenInfo.getTokenName();
      tokenValue = tokenInfo.getTokenValue();
    }
  }

  @Test
  void login() {
    assertThat(tokenName).isNotEmpty();
    assertThat(tokenValue).isNotEmpty();
  }
}
